package cn.com.ry.framework.application.meteor.framework.spring;

import org.springframework.core.io.ClassPathResource;

import java.io.*;

public class SpringTool {
    /**
     * 获取resouce中文件
     *
     * @return
     * @throws IOException
     */
    public static byte[] getResourceBytes(String resourcePath) throws IOException {
        byte[] result = null;
        ClassPathResource classPathResource = new ClassPathResource(resourcePath);
        InputStream arthasInputStream = classPathResource.getInputStream();
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据
        int rc = 0;
        while ((rc = arthasInputStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        arthasInputStream.close();
        arthasInputStream = null;
        result = swapStream.toByteArray();
        swapStream.close();
        swapStream = null;
        return result;
    }

    /**
     * 获取项目地址
     *
     * @return
     */
    public static String getProjectPath() {
        return System.getProperty("user.dir");
    }


    /**
     * 根据byte数组，生成文件
     * filePath  文件路径
     * fileName  文件名称（需要带后缀，如*.jpg、*.java、*.xml）
     */
    public static void saveFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && !dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
